/*
 *  Copyright (C) 2010 fabien
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.boc.botv.common;

import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author fabien
 */
public class Database {

    private static final SessionFactory sessionFactory;
    private static Session current;
    private static boolean isReadOnly;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void startTransaction(boolean readOnly) {
        isReadOnly = readOnly;
        current = Database.getSessionFactory().openSession();
        current.beginTransaction();
    }

    public static Session getSession() {
        return current;
    }

    public static void closeTransaction() {
        Transaction t = current.getTransaction();
        if (!isReadOnly) {
            try {
                t.commit();
            }
            catch (Exception e) {
                t.rollback();
            }
        } else {
            current.close();
        }
    }
}
